<script setup>
  import { ref, reactive, onMounted, computed } from 'vue'
  import { getGlobal } from '/lib/utils/global.js'
  import Pds from './lib/Pds.js'

  const global = getGlobal()
  const state = reactive({
    state: '',
    progress: 0,
    url: ''
  })

  const fileList = ref([])
  const pds = new Pds()
  console.log(pds)

  async function getListFile() {
    global.$pop.loading.open()
    fileList.value = await pds.getListFiles()
    global.$pop.loading.close()
  }

  async function deleteFile({ file_id } = {}, index) {
    global.$pop.loading.open()
    await pds.deleteFile(file_id)
    fileList.value.splice(index, 1)
    global.$pop.loading.close()
  }

  async function onChange(e) {
    const file = e.target.files[0]
    // global.$pop.loading.open()
    let res = await pds.uploadFile(file, {
      onProgress(s, progress) {
        state.state = s
        state.progress = progress
      }
    })
    state.progress = 0
    state.state = ''
    const { file_id } = res
    let { url } = await pds.getFileDownloadUrl(file_id)

    // global.$pop.loading.close()
    state.url = url
    e.target.value = ''

    getListFile()
  }

  const isReady = ref(pds.isReady)

  pds.onMounted(() => {
    isReady.value = pds.isReady

    getListFile()
  })

</script>

<template>
  <div class="p-2" v-if="isReady">
    <!-- isReady{{isReady}} {{pds.access_token}} -->
    <a :href="pds.codeUrl">获取code</a>

    <div class="flex gap-4 p-4">
      <button class="p-4 text-white bg-indigo-500" @click="getListFile">获取文件列表</button>
    </div>



    <div class="p-4">
      <div v-if="state.progress > 0">{{state.state}}: {{state.progress}}%</div>
      <input type="file" @change="onChange" v-else />
      <a :href="state.url" download class="px-8 py-2 text-white bg-blue-500 rounded" v-if="state.url">下载</a>

    </div>


    <ul class="space-y-4">
      <li v-for="d, i in fileList" :key="d.upload_id" class="relative flex items-center border rounded">
        <img :src="d.thumbnail" class="object-cover w-20 bg-black/50 aspect-square" />
        <div class="flex-1 p-2 space-y-2">
          <div>{{d.file_id}}</div>
          <div class="flex gap-4">
            <a :href="d.url" download class="px-8 py-2 text-white bg-blue-500 rounded">下载</a>
            <button class="px-8 py-2 text-white bg-red-500 rounded" @click="deleteFile(d, i)">删除</button>
          </div>
        </div>

        <span class="absolute top-0 right-0 px-2 py-0.5 text-sm text-white rounded bg-black/50">{{d.file_extension}}</span>
      </li>
    </ul>

  </div>
</template>

<style scoped>

</style>